<?php

namespace frontend\controllers;

use bc\controller\WxOAuthController;
use bc\model\coupons\CouponsUserModel;
use bc\model\coupons\CouponsModel;
use bc\model\coupons\ReceiveModel;
use bc\model\coupons\ShareModel;
use bc\model\ProductModel;
use bc\model\wx\User;
use yii\base\Exception;
use yii\web\Session;

class CouponController extends WxOAuthController
{
	
	/**
	 * 1 => 未使用
	 * 2 => 使用记录
	 * 3 => 已过期
	 * 
	 * @var array $arrType
	 */
	protected $arrType = [1, 2, 3];

	/**
	 * 优惠券列表
	 */
	public function actionList()
	{
		$date=date("Y-m-d H:i:s");
		$type = $this->get('type', 0);
		$model = new CouponsModel();
		$model->sort = 'bc_coupons_user.create_time DESC';

		$session=new Session();
		$user_info=$session->get('shop_user');
		$userId = $user_info['user_id'];
		$model = new CouponsModel();
		$model->sort = 'bc_coupons_user.create_time DESC';
		$model->columns='count(bc_coupons_user.status) as total, bc_coupons_user.status, bc_coupons.coupons_name,bc_coupons.product_id,
						bc_coupons.coupons_type,bc_coupons.coupons_full_money,bc_coupons.coupons_money,bc_coupons.coupons_release_type,
						bc_coupons.release_start_time,bc_coupons.release_end_time,
						bc_coupons.use_start_time,bc_coupons.use_end_time,bc_coupons.coupons_id as couponsid,
						CASE
        					WHEN `bc_coupons`.`use_end_time` < \''.$date.'\' and `bc_coupons_user`.`status`=0 THEN 4
							WHEN `bc_coupons`.`use_end_time` < \''.$date.'\' and `bc_coupons_user`.`status`=1 THEN 1
							WHEN `bc_coupons`.`use_end_time` < \''.$date.'\' and `bc_coupons_user`.`status`=2 THEN 4
							WHEN `bc_coupons`.`use_end_time` < \''.$date.'\' and `bc_coupons_user`.`status`=3 THEN 4
        					WHEN `bc_coupons`.`use_end_time` >= \''.$date.'\' and `bc_coupons_user`.`status`=0 THEN 0
							WHEN `bc_coupons`.`use_end_time` >= \''.$date.'\' and `bc_coupons_user`.`status`=1 THEN 1
							WHEN `bc_coupons`.`use_end_time` >= \''.$date.'\' and `bc_coupons_user`.`status`=2 THEN 2
							WHEN `bc_coupons`.`use_end_time` >= \''.$date.'\' and `bc_coupons_user`.`status`=3 THEN 3
   						END as coupons_status,sum(bc_coupons_user.is_back_send) as is_back_send_total';

		$list=$model->getCouponInfo($userId,$type);

		$view['totalList']=$model->getCouponTotalFromStatus($userId,$date);
		$view['list'] = $list;
		$view['type'] = $type;
		$view['js_config']=$this->configJsApi();
		$base_url=$this->getBaseUrl();
		$view['base_url']=$base_url;
		return $this->render('expired', $view);
	}
	/**
	 * Created by Mr.hu.
	 * Description:优惠券的转赠
	 */
	public function actionShare()
	{
		//用户的信息
		$session=new Session();
		$user_info=$session->get('shop_user');

		//post参数
		$unique_code=$this->post('unique_code');//唯一编码
		$number= intval($this->post('number'));//数量
		$coupon_id=intval($this->post('coupon_id')); //优惠券的id
		$now_time=date('Y-m-d H:i:s');
		//检查用户赠送优惠券的可靠性
		if(!$this->check_share_info($user_info['user_id'],$coupon_id,$number)){
			$return=array(
				'status'=>0,
				'msg'=>'分享的数量超出限制',
			);
			exit(json_encode($return,0));
		}

		//查找用户的未使用的优惠券，从中抽取一定数量赠送出去
		$rand_list=CouponsUserModel::find()
			->where(['user_id'=>$user_info['user_id'],'coupons_id'=>$coupon_id,'status'=>0,'from_user_id'=>0])
			->limit($number)
			->asArray()
			->all();
		$coupon_ids=array_column($rand_list,'coupons_user_id');

		//组合分享表的数据
		$insert_data=array(
			'unique_code'=>$unique_code,
			'coupons_id'=>$coupon_id,
			'user_id'=>$user_info['user_id'],
			'coupons_number'=>$number,
			'status'=>0,
			'create_time'=>$now_time,
			'update_time'=>$now_time,
			'is_del'=>0,
			'coupons_user_ids'=>implode(',',$coupon_ids)
		);

		$activeModel=\Yii::$app->db;
		$transaction =$activeModel->beginTransaction();
		try{
			//更新
			CouponsUserModel::updateAll(
				['status'=>2,'update_time'=>$now_time],
				['coupons_user_id'=>$coupon_ids]
				);

			$shareModel=new ShareModel();
			//添加
			$shareModel->add($insert_data);
			$transaction ->commit();
			exit(json_encode(array('status'=>1,'msg'=>'转赠成功'),0));
		}catch (\Exception $e){
			$transaction->rollBack();
			exit(json_encode(array('status'=>0,'msg'=>'转赠失败'),0));
		}

	}

	/**
	 * Created by Mr.hu.
	 * @param $uid 用户的uid
	 * @param $coupon_id 优惠券的id
	 * @param $number 优惠券的数量
	 * Description:检查用户分享的优惠券的数量是否符合条件
	 */
	private function check_share_info($uid,$coupon_id,$number)
	{
			$exist=CouponsUserModel::find()
				->where(['user_id'=>$uid,'coupons_id'=>$coupon_id,'status'=>0,'from_user_id'=>0])
				->count();
			return	$number <=  $exist	;
	}


	/**
	 * Created by Mr.hu.
	 * Description:优惠券领取的展示页面
	 */
	public function actionReceive()
	{
		$coupons_code=$this->get('coupon_code');
		//根据优惠券的code，获取对应的信息
		$coupon_info=$this->get_coupons_info($coupons_code);
		$coupon_info['coupon_code']=$coupons_code;
		return  $this->render('receive',$coupon_info);
	}


	/**
	 * Created by Mr.hu.
	 * Description；是否可以领取优惠券
	 */
	public function actionCheck()
	{
		$sessionObj=new Session();
		$self_info=$sessionObj->get('shop_user');
		$coupons_code=$this->get('coupon_code');
		$coupons_share_info=ShareModel::findOne(['unique_code'=>$coupons_code]);
		$coupons_info=CouponsModel::findOne(['coupons_id'=>$coupons_share_info['coupons_id']]);
		$error_msg=array(
			'money'=>	$coupons_info['coupons_money'],
			'product_name'=>$coupons_info['coupons_type']==2?'满'.$coupons_info['coupons_full_money'].'可用':'',
		);
		$if_lock=true;
		//优惠券不存在
		if(!$coupons_share_info){
				$error_msg['msg']='无效领取';
				$if_lock=false;
				return $this->render('fail',$error_msg);
		}

		//检查优惠券是否被收回
		if($coupons_share_info['status']==1){
			$error_msg['msg']='该优惠券已被收回';
			$if_lock=false;
			return $this->render('fail',$error_msg);
		}

		//优惠券已领完
		if($coupons_share_info['coupons_number']==0){
				$error_msg['msg']='该优惠券已领完';
				$if_lock=false;
				return $this->render('fail',$error_msg);
		}

		//优惠券是否过期
		$now_time=date('Y-m-d H:i:s');
		if($now_time>=$coupons_info['use_end_time']){
			$error_msg['msg']='该优惠券已过期~';
			$if_lock=false;
			return $this->render('fail',$error_msg);
		}

		//是否真的是对方分享的优惠券
		$coupons_user_ids=explode(',',$coupons_share_info['coupons_user_ids']);
		if(!$coupons_user_ids){
			$if_lock=false;
			$error_msg['msg']='无效领取';
			return $this->render('fail',$error_msg);
		}

		//检查用户的优惠券数量是否超出限制
		if($this->check_over_limit($self_info['user_id'],$coupons_share_info['coupons_id'],$coupons_info['coupons_limit_number'])){
			$error_msg['msg']='该优惠券您已达到领取上限。';
			$if_lock=false;
			return $this->render('fail',$error_msg);
		}


		if($if_lock){
		//进行领取操作

		$model=\Yii::$app->db;
		$lock=$model->beginTransaction();
		//查找 出一张优惠券赠送中的优惠券
		$one_coupons_info=CouponsUserModel::find()
			->where(['coupons_user_id'=>$coupons_user_ids,'status'=>2])
			->limit(1)
			->asArray()
			->one();

		if(!$one_coupons_info){
			$lock->rollBack();
			$error_msg['msg']='该优惠券已领完';
			return	$this->render('fail',$error_msg);
		}



		$add_receive_data=array(
			'share_id'=>$coupons_share_info['coupons_share_id'],
			'coupons_user_id'=>$one_coupons_info['coupons_user_id'],
			'from_user_id'=>$coupons_share_info['user_id'],
			'user_id'=>$self_info['user_id'],
			'old_from_user_id'=>$one_coupons_info['from_user_id'],
			'create_time'=>$now_time,
			'update_time'=>$now_time,
			'is_del'=>0
		);


		//更新share数据
//		$model->createCommand("")->execute();
		$shareModel=ShareModel::findOne(['coupons_share_id'=>$coupons_share_info['coupons_share_id']]);
		$shareModel->coupons_number-=1;
		$result1=$shareModel->save();

		//添加数据receive表的数据
		$receiveMode=new ReceiveModel();
		$result2=$receiveMode->add($add_receive_data);

		//更新coupons—user拥有者的信息
		$couponsUserModel=CouponsUserModel::findOne(['coupons_user_id'=>$one_coupons_info['coupons_user_id']]);
		$couponsUserModel->user_id=$self_info['user_id'];
		$couponsUserModel->from_user_id=$coupons_share_info['user_id'];
		$couponsUserModel->is_back_send=0;
		$couponsUserModel->status=0;
		$couponsUserModel->update_time=$now_time;
		$result3=$couponsUserModel->save();

		if($result1&&$result2&&$result3){
			$lock->commit();
			//展现成功的页面
			$coupon_info=$this->get_coupons_info($coupons_code);
			return	$this->render('success',$coupon_info);
		}else{
			$lock->rollBack();
			$error_msg['msg']='该优惠券已领完';
			return	$this->render('fail',$error_msg);
		}

		}

	}


	/**
	 * Created by Mr.hu.
	 * @param $coupons_code
	 * Description:根据将优惠券的唯一编码，获取优惠券的信息
	 */
	private function get_coupons_info($coupons_code)
	{
			//分享信息
			$shareInfo=ShareModel::findOne(['unique_code'=>$coupons_code]);
			if(empty($shareInfo)){return false;}

			//优惠券信息
			$couponsInfo=CouponsModel::findOne(['coupons_id'=>$shareInfo['coupons_id']]);
			if(empty($couponsInfo)){return false;}

			//用户个人信息
			$userInfo=User::find()
				->from(User::tableName().' as   wxu')
				->innerJoin('ecs_users as ecu','wxu.openid=ecu.wxid')
				->where(['ecu.user_id'=>$shareInfo['user_id']])
				->select('wxu.nickname,wxu.headimgurl,wxu.openid')
				->asArray()
				->one();

			return array(
				'product_id'=>$couponsInfo['product_id'],
				'money'=>$couponsInfo['coupons_money'],
				'type_text'=>$couponsInfo['coupons_type']==2?'满'.$couponsInfo['coupons_full_money'].'可用':'',
				'header_url'=>$userInfo['headimgurl'],
				'nickname'=>$userInfo['nickname'],
				'product_name'=>$this->get_product_name($couponsInfo['coupons_use_target'],$couponsInfo['product_id'],$couponsInfo['product_group_id']),
				'use_start_time'=>self::date_format($couponsInfo['use_start_time']),
				'use_end_time'=>self::date_format($couponsInfo['use_end_time'])
			);
	}

	/**
	 * Created by Mr.hu.
	 * @param $data
	 * Description:格式化日期
	 */
	static private function date_format($data)
	{
		return date('Y.m.d H:i',strtotime($data));
	}

	/**
	 * Created by Mr.hu.
	 * @param $type 优惠券使用类型
	 * @param $product_id
	 * @param $product_group_id
	 * Description:根据优惠券的使用类型，获取对应的产品名称
	 */
	private function get_product_name($type,$product_id,$product_group_id)
	{
		switch ($type){
			//单个产品
			case 1:
				$name=ProductModel::find()
					->where(['product_id'=>$product_id])
					->select('product_name')
					->asArray()
					->one();
				return $name['product_name'];
				break;
				//产品组
			case 2:
				return 'this is product_group_name...';
				break;
			case 3:
				return '全场通用';
				break;
		}

	}


	/**
	 * Created by Mr.hu.
	 * @param $uid 用户的id
	 * @param $coupon_id 优惠券的id
	 * @param $limit 上限值
	 * Description:检查用户拥有的优惠券是否超过了限制
	 */
	private function check_over_limit($uid,$coupon_id,$limit)
	{
			$count=CouponsUserModel::find()
				->where(['and','coupons_id='.$coupon_id,['or','user_id='.$uid,'from_user_id='.$uid]])
				->count();
			return	intval($count)>=intval($limit)?true:false;
	}


	/**
	 * Created by Mr.hu.
	 * Description:撤销优惠券
	 */
	public function actionUndo()
	{
		//优惠券的id
		$coupon_id=$this->post('coupon_id');
		//用户的个人信息
		$self_info=(new Session())->get('shop_user');
		if($coupon_id&&$self_info){
				$lock=\Yii::$app->db->beginTransaction();
				try{
					ShareModel::updateAll(['status'=>1],['coupons_id'=>$coupon_id,'user_id'=>$self_info['user_id'],'status'=>0]);
					$cx_count=CouponsUserModel::updateAll(['status'=>0],['coupons_id'=>$coupon_id,'user_id'=>$self_info['user_id'],'status'=>2]);
					$lock->commit();
					exit(json_encode(array('status'=>1,'msg'=>'已撤销'.$cx_count.'张优惠券'),0));
				}catch (Exception $e){
					$lock->rollBack();
					exit(json_encode(array('status'=>0,'msg'=>'撤回失败'),0));
				}
		}else{
			exit(json_encode(array('status'=>0,'msg'=>'无效的参数'),0));
		}
	}


	/**
	 * Created by Mr.hu.
	 * Description:检查用户转增出去的数量是否符合
	 */
	public function actionCheckNumber()
	{
		//用户的信息
		$session=new Session();
		$user_info=$session->get('shop_user');
		$coupon_id=$this->post('coupon_id');
		$number=CouponsUserModel::find()
			->where(['user_id'=>$user_info['user_id'],'coupons_id'=>$coupon_id,'status'=>0,'from_user_id'=>0])
			->count();
		exit(json_encode(array('number'=>$number)));
	}


	
	
	
}

